package com.lotea.android.andreaditlater.ui.adapters;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filterable;

import com.lotea.android.andreaditlater.R;
import com.lotea.android.andreaditlater.data.db.DbAdapter;
import com.lotea.android.andreaditlater.ui.widgets.ReadListItem;

public class ItemListAdapter extends CursorAdapter implements Filterable {

	private final LayoutInflater mInflater;
	private Cursor mCursor;
	private DbAdapter mDbAdapter;

	public ItemListAdapter(Context context, Cursor c, DbAdapter dbAdapter) {
		super(context, c);
		mInflater = LayoutInflater.from(context);
		mCursor = c;
		mDbAdapter = dbAdapter;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		ReadListItem item = (ReadListItem) view;

		item.setTitle(cursor.getString(cursor
				.getColumnIndexOrThrow(DbAdapter.Columns.Items.TITLE)));
		item.setUrl(cursor.getString(cursor
				.getColumnIndexOrThrow(DbAdapter.Columns.Items.URL)));
		item.setTags(cursor.getString(cursor.getColumnIndexOrThrow("tags")));
		item.setTime(cursor.getLong(cursor
				.getColumnIndexOrThrow(DbAdapter.Columns.Items.TIME_ADDED)));
		item.setId(cursor.getInt(cursor
				.getColumnIndexOrThrow(DbAdapter.Columns.ID)));

		if (cursor.getInt(cursor
				.getColumnIndexOrThrow(DbAdapter.Columns.Items.STATE)) == 0) {
			item.markAsUnread();
		} else {
			item.markAsRead();
		}
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		return mInflater.inflate(R.layout.read_list_item, null);
	}

	@Override
	public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
		if (constraint != null) {
			StringBuilder builder = new StringBuilder();
			builder.append("UPPER(");
			builder.append(DbAdapter.Columns.Items.TITLE);
			builder.append(") GLOB ? OR ");
			builder.append("UPPER(");
			builder.append(DbAdapter.Columns.Items.URL);
			builder.append(") GLOB ? OR ");
			builder.append("UPPER(");
			builder.append("tags");
			builder.append(") GLOB ?");

			final String arg = "*" + constraint.toString().toUpperCase() + "*";
			final String[] selectionArgs = new String[] { arg, arg, arg };

			Cursor cursor = mDbAdapter.queryItems(builder.toString(),
					selectionArgs);

			return cursor;

		} else {
			return super.runQueryOnBackgroundThread(constraint);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.BaseAdapter#notifyDataSetChanged()
	 */
	@Override
	public void notifyDataSetChanged() {
		// mCursor.requery();
		super.notifyDataSetChanged();
	}
}
